package com.shiro.receiver.framework.interceptor;

import cn.hutool.extra.servlet.JakartaServletUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.NonNull;
import com.shiro.receiver.entity.Payload;
import com.shiro.receiver.entity.req.CallbackVerificationReqData;
import com.shiro.receiver.framework.annotation.Interceptor;
import com.shiro.receiver.framework.constant.BotOperationType;
import com.shiro.receiver.framework.properties.BotProperties;
import com.shiro.receiver.util.Ed25519Util;

import java.io.PrintWriter;
import java.util.List;

@Interceptor
@RequiredArgsConstructor
public class CallbackVerificationInterceptor implements WebInterceptor {

    private final BotProperties botProperties;

    private final TypeReference<Payload<JSONObject>> TYPE_REFERENCE = new TypeReference<>() {};

    @Override
    public String getName() {
        return "回调验证拦截器";
    }

    @Override
    public Integer getOrder() {
        return 49;
    }

    @Override
    public boolean isEnable() {
        if (botProperties.getInterceptors() == null ||botProperties.getInterceptors().getCallbackVerificationInterceptor() == null) {
            return false;
        }
        return Boolean.TRUE.equals(botProperties.getInterceptors().getCallbackVerificationInterceptor().getEnabled());
    }

    @Override
    public List<String> getPathPatterns() {
        return List.of("/callback");
    }

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        String requestBody = JakartaServletUtil.getBody(request);
        Payload<JSONObject> payload = JSONObject.parseObject(requestBody, TYPE_REFERENCE);
        if (!BotOperationType.isCallbackHostCheck(payload.getOperationType())) {
            return true;
        }
        CallbackVerificationReqData callbackVerificationReqData = payload.getData().toJavaObject(CallbackVerificationReqData.class);
        String message = callbackVerificationReqData.getEventTimestamp() + callbackVerificationReqData.getPlainToken();
        String signature = Ed25519Util.signToHexString(botProperties.getConfig().getAppSecret(), message);
        JSONObject responseBody = new JSONObject();
        responseBody.put("plain_token", callbackVerificationReqData.getPlainToken());
        responseBody.put("signature", signature);
        // 返回处理完的内容
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter responseWriter = response.getWriter();
        responseWriter.write(responseBody.toJSONString());
        responseWriter.flush();
        return false;
    }

}
